<template>
  <a-card :bordered="false">
    <!-- table区域-begin -->
    <div>
      <a-tabs v-model="activeKey" @change="handleChangeTab">
        <a-tab-pane key='0' tab="包装投料">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label="包装车间">
                  <j-search-select-tag
                    type="list"
                    v-model="queryParamFeeding.packshopCode"
                    :dictOptions="dictOptions"
                    placeholder="请选择所属车间"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="10" :lg="11" :md="12" :sm="24">
                <a-form-item label="制单日期">
                  <j-date placeholder="请选择开始日期" class="query-group-cust" v-model="queryParamFeeding.createTime_begin"></j-date>
                  <span class="query-group-split-cust"></span>
                  <j-date placeholder="请选择结束日期" class="query-group-cust" v-model="queryParamFeeding.createTime_end"></j-date>
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <!-- <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button> -->
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 查询区域-END -->
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button @click="handleAdd" type="primary" icon="plus">添加</a-button>
        </div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
          <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          <span style="float:right;">
            <a-popover title="自定义列" trigger="click" placement="leftBottom">
              <template slot="content">
                <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                  <a-row style="width: 400px">
                    <template v-for="(item,index) in defColumns">
                      <template v-if="item.key!=='rowIndex'&& item.dataIndex!=='action'">
                          <a-col :span="12"><a-checkbox :value="item.dataIndex"><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox></a-col>
                      </template>
                    </template>
                  </a-row>
                </a-checkbox-group>
              </template>
              <a><a-icon type="setting" />设置</a >
            </a-popover>
          </span>
        </div>
          <a-table
            ref="feedingTable"
            size="middle"
            :scroll="{x:true}"
            bordered
            rowKey="id"
            :columns="feedingColumns"
            :dataSource="feedingTable.dataSource"
            :pagination="feedingTable.ipagination"
            :loading="feedingTable.loading"
            :rowSelection="{selectedRowKeys: feedingSelectedRowKeys, onChange: onSelectChangeFeeding, type: 'radio'}"
            class="j-table-force-nowrap1"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text,record">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
              <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
              <a-button
                v-else
                :ghost="true"
                type="primary"
                icon="download"
                size="small"
                @click="downloadFile(text)">
                下载
              </a-button>
            </template>

            <span slot="action" slot-scope="text, record">
              <a @click="handlePackage(record)">包材清单</a>
            </span>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key='1' tab="投料记录">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <a-form-item label="包装车间">
                    <j-search-select-tag
                      type="list"
                      v-model="queryParamRecord.packshopCode"
                      :dictOptions="dictOptions"
                      placeholder="请选择所属车间"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="10" :lg="11" :md="12" :sm="24">
                  <a-form-item label="操作日期">
                    <j-date placeholder="请选择开始日期" class="query-group-cust" v-model="queryParamRecord.createTime_begin"></j-date>
                    <span class="query-group-split-cust"></span>
                    <j-date placeholder="请选择结束日期" class="query-group-cust" v-model="queryParamRecord.createTime_end"></j-date>
                  </a-form-item>
                </a-col>
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                    <!-- <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button> -->
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
            <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
            >项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
            <span style="float:right;">
              <a-popover title="自定义列" trigger="click" placement="leftBottom">
                <template slot="content">
                  <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                    <a-row style="width: 400px">
                      <template v-for="(item,index) in defColumns">
                        <template v-if="item.key!=='rowIndex'&& item.dataIndex!=='action'">
                            <a-col :span="12"><a-checkbox :value="item.dataIndex"><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox></a-col>
                        </template>
                      </template>
                    </a-row>
                  </a-checkbox-group>
                </template>
                <a><a-icon type="setting" />设置</a >
              </a-popover>
            </span>
          </div>
          <!-- 查询区域-END -->
          <a-table
            ref="recordTable"
            size="middle"
            :scroll="{x:true}"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="recordTable.dataSource"
            :pagination="recordTable.ipagination"
            :loading="recordTable.loading"
            class="j-table-force-nowrap1"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text,record">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
              <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
              <a-button
                v-else
                :ghost="true"
                type="primary"
                icon="download"
                size="small"
                @click="downloadFile(text)">
                下载
              </a-button>
            </template>

            <span slot="action" slot-scope="text, record">
              <a @click="handleDetail(record)">详情</a>
              <a-divider type="vertical" />
              <a @click="handleWithdraw(record)">撤回</a>
            </span>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>

    <erp-package-feeding-modal ref="modalForm" @ok="modalFormOk"></erp-package-feeding-modal>

    <erp-package-detail-modal ref="ErpPackageDetailModal" @ok="modalFormOk"></erp-package-detail-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ErpPackageFeedingModal from './modules/ErpPackageFeedingModal.vue'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import { getAction } from '@/api/manage'
  import ErpPackageDetailModal from '../manufactureconfirm/packageprocessconfirmation/modules/ErpPackageDetailModal.vue'
  import dayjs from 'dayjs'
  import { getDate } from '../../../utils'

  export default {
    name: 'ErpPackageFeedingList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      ErpPackageFeedingModal,
      ErpPackageDetailModal
    },
    data () {
      return {
        description: '包装投料管理页面',
        // 包装投料表头
        feedingColumns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'计划单号',
            align:"center",
            dataIndex: 'planCode'
          },
          {
            title:'订单编号',
            align:"center",
            dataIndex: 'orderCode'
          },
          {
            title:'物料名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'规格型号',
            align:"center",
            dataIndex: 'materialSpec'
          },
          {
            title:'配方号',
            align:"center",
            dataIndex: 'formulaNumber'
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'meUnit_dictText'
          },
          {
            title:'计划数量',
            align:"center",
            dataIndex: 'planQuantity'
          },
          {
            title:'包装车间',
            align:"center",
            dataIndex: 'packshopCode_dictText'
          },
          {
            title:'生产车间',
            align:"center",
            dataIndex: 'workshopCode_dictText'
          },
          {
            title:'执行日期',
            align:"center",
            dataIndex: 'workTime'
          },
          {
            title:'制单人',
            align:"center",
            dataIndex: 'createBy_dictText'
          },
          {
            title:'制单日期',
            align:"center",
            dataIndex: 'createTime',
            customRender:function (text) {
              return !text?'':(dayjs(text).format('YYYY-MM-DD'))
            }
          },
          {
            title:'是否变更计划',
            align:"center",
            dataIndex: 'isUpdate_dictText'
          },
          {
            title:'包装投料',
            align:"center",
            dataIndex: 'recordTimes'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:100,
            scopedSlots: { customRender: 'action' },
          }
        ],
        // 投料记录表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'投料记录单号',
            align:"center",
            dataIndex: 'feedingRecordCode'
          },
          {
            title:'单据类型',
            align:"center",
            dataIndex: 'documentType_dictText'
          },
          {
            title:'计划单号',
            align:"center",
            dataIndex: 'planCode'
          },
          {
            title:'订单编号',
            align:"center",
            dataIndex: 'orderCode'
          },
          {
            title:'物料名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'规格型号',
            align:"center",
            dataIndex: 'materialSpec'
          },
          {
            title:'配方号',
            align:"center",
            dataIndex: 'formulaNumber'
          },
          {
            title:'生产车间',
            align:"center",
            dataIndex: 'workshopCode_dictText'
          },
          {
            title:'包装车间',
            align:"center",
            dataIndex: 'packshopCode_dictText'
          },
          {
            title:'执行日期',
            align:"center",
            dataIndex: 'workTime'
          },
          {
            title:'操作人',
            align:"center",
            dataIndex: 'createBy_dictText'
          },
          {
            title:'操作部门',
            align:"center",
            dataIndex: 'sysOrgCode_dictText'
          },
          {
            title:'操作时间',
            align:"center",
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          //投料记录列表
          list: "/feedingpackage/erpPackageFeeding/list",
          delete: "/feedingpackage/erpPackageFeeding/delete",
          deleteBatch: "/feedingpackage/erpPackageFeeding/deleteBatch",
          exportXlsUrl: "/feedingpackage/erpPackageFeeding/exportXls",
          importExcelUrl: "feedingpackage/erpPackageFeeding/importExcel",
          //撤回
          withdrawRecord: "feedingpackage/erpPackageFeeding/withdrawRecord",
          //包材投料列表
          // packagePlanList: "/pro/tslProWorkshopPlan/queryPackageList",
          packagePlanList: "/feedingpackage/erpPackageFeeding/packshopPlanList",
        },
        dictOptions:[],
        superFieldList:[],
        activeKey: '0',
        // 选择的包装投料
        feedingSelectionRows: [],
        feedingSelectedRowKeys: [],
        selectedRowKeys: [],
        //查询条件
        queryParamFeeding:{
          createTime_begin:'',
          createTime_end:'',
          packshopCode: null,
        },
        queryParamRecord:{
          createTime_begin:'',
          createTime_end:'',
          packshopCode: null,
        },
        //包装投料列表数据
        feedingTable: {
          loading: false,
          dataSource: [],
          // 表头
          ipagination: {
            current: 1,
            pageSize: 30,
            pageSizeOptions: ['10', '20', '30'],
            showTotal: (total, range) => {
              return range[0] + '-' + range[1] + ' 共' + total + '条'
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0,
          },
        },
        //投料记录列表数据
        recordTable: {
          loading: false,
          dataSource: [],
          // 表头
          ipagination: {
            current: 1,
            pageSize: 30,
            pageSizeOptions: ['10', '20', '30'],
            showTotal: (total, range) => {
              return range[0] + '-' + range[1] + ' 共' + total + '条'
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0,
          },
        },
        settingColumns: [],
      }
    },
    created() {
      this.queryParamFeeding.createTime_begin = getDate('day', -7)
      this.queryParamFeeding.createTime_end = getDate('day', 0)
      this.queryParamRecord.createTime_begin = getDate('day', -7)
      this.queryParamRecord.createTime_end = getDate('day', 0)
      this.getSuperFieldList();
      // 获取车间字典，默认选择第一个
      this.loadworkshopDict();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    watch: {
      // 对车间选择的监听
      'queryParamFeeding.packshopCode': {
        handler(newVal, oldVal) {
          // 当车间变化时自动触发查询
          if (newVal !== oldVal) {
            this.handleWorkshopChange();
          }
        },
        immediate: false
      },
      'queryParamRecord.packshopCode': {
        handler(newVal, oldVal) {
          // 当车间变化时自动触发查询
          if (newVal !== oldVal) {
            this.handleWorkshopChange();
          }
        },
        immediate: false
      },
    },
    methods: {
      // 加载车间字典 --> 默认选择第一条下拉数据
      loadworkshopDict(){
        getAction(`/sys/dict/getDictItems/erp_package_organization,depart_name,depart_code`,{}).then(res=>{
          if(res.success){
            this.dictOptions = res.result.map(item => ({value: item.value, text: item.text}))
            if(this.dictOptions.length > 0 || this.dictOptions.length > 0){
              this.queryParamFeeding.packshopCode = this.dictOptions[0].value
              this.queryParamRecord.packshopCode = this.dictOptions[0].value
            }
          } else {
            console.error('getDictItems error: : ', res)
            this.dictOptions = []
          }
        })
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
         fieldList.push({type:'string',value:'feedingRecordCode',text:'投料记录单号',dictCode:''})
         fieldList.push({type:'int',value:'ifWithdraw',text:'是否撤回',dictCode:''})
         fieldList.push({type:'string',value:'planCode',text:'计划单号',dictCode:''})
         fieldList.push({type:'string',value:'planId',text:'生产计划id',dictCode:''})
         fieldList.push({type:'string',value:'materialName',text:'物料名称',dictCode:''})
         fieldList.push({type:'string',value:'materialCode',text:'物料编码',dictCode:''})
         fieldList.push({type:'string',value:'materialSpec',text:'规格型号',dictCode:''})
         fieldList.push({type:'string',value:'packshopCode',text:'包装车间',dictCode:''})
         fieldList.push({type:'int',value:'timesNumber',text:'包装投料次数',dictCode:''})
        this.superFieldList = fieldList
      },
      // 修改查询方法
      searchQuery() {
         // 重置为第一页
        if (this.activeKey === '0') {
          this.feedingTable.ipagination.current = 1;
        } else {
          this.recordTable.ipagination.current = 1;
        }
        // 调用查询
        this.loadFeedingRecordData()
      },
      // 修改重置方法
      searchReset() {
        // 重置查询参数
        this.queryParamFeeding = {
          createTime_begin: '',
          createTime_end: '',
          packshopCode: null,
          // 保留分页参数
          pageNo: this.activeKey === '0' 
            ? this.feedingTable.ipagination.current 
            : this.recordTable.ipagination.current,
          pageSize: this.activeKey === '0' 
            ? this.feedingTable.ipagination.pageSize 
            : this.recordTable.ipagination.pageSize
        };
        this.queryParamRecord = {
          createTime_begin: '',
          createTime_end: '',
          packshopCode: null,
          // 保留分页参数
          pageNo: this.activeKey === '0' 
            ? this.feedingTable.ipagination.current 
            : this.recordTable.ipagination.current,
          pageSize: this.activeKey === '0' 
            ? this.feedingTable.ipagination.pageSize 
            : this.recordTable.ipagination.pageSize
        };
        // 重置为第一页
        if (this.activeKey === '0') {
          this.feedingTable.ipagination.current = 1;
        } else {
          this.recordTable.ipagination.current = 1;
        }
        // 调用重置并刷新数据
        this.loadFeedingRecordData()
      },
      //this.activeKey：0为包装投料，1为投料记录。
      loadFeedingRecordData() {
        let urlList = this.url.packagePlanList
        let tableRef = this.activeKey === '0' 
          ? 'feedingTable' 
          : 'recordTable';
        // 设置加载状态
        this[tableRef].loading = true;
        urlList = this.activeKey === '0' 
            ? this.url.packagePlanList 
            : this.url.list;
        // 获取当前表格的分页参数
        const pagination = this.activeKey === '0' 
          ? this.feedingTable.ipagination 
          : this.recordTable.ipagination;
        // 设置查询参数
        const queryParam = this.activeKey === '0' 
          ? this.queryParamFeeding 
          : this.queryParamRecord;
        const params = {
          ...queryParam,
          pageNo: pagination.current,
          pageSize: pagination.pageSize
        };
        getAction(urlList, params)
          .then((res) => {
            if (res.success) {
              this[tableRef].dataSource = res.result.records || res.result || [];
              if (res.result.total) {
                this[tableRef].ipagination.total = res.result.total;
              } else {
                this[tableRef].ipagination.total = 0;
              }
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this[tableRef].loading = false;
          })
          this.feedingSelectedRowKeys = [];
          this.feedingSelectionRows = [];
      },
      handleChangeTab() {
        this.loadFeedingRecordData()
      },
      // 修改：添加分页处理方法
      handleTableChange(pagination, filters, sorter, { currentDataSource }) {
        // 根据当前激活的标签页更新对应的分页参数
        if (this.activeKey === '0') {
          this.feedingTable.ipagination = {
            ...this.feedingTable.ipagination,
            current: pagination.current,
            pageSize: pagination.pageSize
          };
        } else {
          this.recordTable.ipagination = {
            ...this.recordTable.ipagination,
            current: pagination.current,
            pageSize: pagination.pageSize
          };
        }
        // 重新加载数据
        this.loadFeedingRecordData();
      },
      // 添加
      handleAdd: function () {
        if (this.queryParamFeeding.packshopCode === '' || this.queryParamFeeding.packshopCode === null) {
            this.$message.warning('请选择车间')
            return
        }
        if (this.feedingSelectionRows.length <= 0) {
            this.$message.warning('请选择包装投料')
            return
        }
        let formData = {
          planId: this.feedingSelectionRows[0].planId,
          planCode: this.feedingSelectionRows[0].planCode,
          orderCode: this.feedingSelectionRows[0].orderCode,
          materialName: this.feedingSelectionRows[0].materialName,
          materialSpec: this.feedingSelectionRows[0].materialSpec,
          formulaNumber: this.feedingSelectionRows[0].formulaNumber,
          workshopCode: this.feedingSelectionRows[0].workshopCode,
          packshopCode: this.feedingSelectionRows[0].packshopCode,
          workTime: this.feedingSelectionRows[0].workTime,
        }
        // 点击添加时，获取当前查询框的车间值并传递给form
        this.$refs.modalForm.getWorkshopCode(formData);
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '添加'
        this.$refs.modalForm.disableSubmit = false
      },
      // 修改modalFormOk方法
      modalFormOk() {
        // 添加成功后刷新列表
        this.loadFeedingRecordData();
      },
      // 包材清单
      handlePackage: function (record) {
        this.$refs.ErpPackageDetailModal.detail(record)
        this.$refs.ErpPackageDetailModal.title = '包材清单'
        this.$refs.ErpPackageDetailModal.disableSubmit = false
      },
      // 撤回
      handleWithdraw: function (record) {
        let that = this;
        that.$confirm({
          title: "投料撤回",
          content: "是否撤回选中数据?",
          onOk: function() {
            that.withdrawRecord(record.id)
            that.onClearSelected();
          }
        });
      },
      async withdrawRecord(id) {
        try {
          const res = await getAction(this.url.withdrawRecord, {id})
          if (res.success) {
            this.$message.success(res.result)
            this.loadFeedingRecordData();
            return res.result
          } else {
            this.$message.warning(res.message)
            return ''
          }
        } catch (e) {
          console.error("撤回失败", e)
          return ''
        }
      },
      // 包装投料 选中时将所选数据的id赋给feedingSelectedRowKeys
      onSelectChangeFeeding(selectedRowKeys, selectionRows) {
        this.feedingSelectedRowKeys = selectedRowKeys
        this.feedingSelectionRows = selectionRows
      },
      // 车间变化处理方法
      handleWorkshopChange() {
          //将所选数据置空
          this.feedingSelectedRowKeys = [];
          this.feedingSelectionRows = [];
          this.recordSelectedRowKeys = [];
          // 重置当前标签页的分页到第一页
          if (this.activeKey === '0') {
            this.feedingTable.ipagination.current = 1;
          } else {
            this.recordTable.ipagination.current = 1;
          }
          // 触发数据加载
          this.loadFeedingRecordData();
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>